# coding:utf-8
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from models import Category, Article, Comments, Visitors
from forms import Nameform, CommentsForm
from encryption import encryption, paginator_page
# Create your views here.


def index(request):
    # 主页
    page = request.GET.get('page')
    article_list = Article.objects.all().order_by('-id')
    categories = Category.objects.all()
    articles_list, num_pages = paginator_page(article_list, page)

    return render(
        request,
        "boot/ghost_green.html",
        {
            "articles": articles_list,
            "categories": categories,
            "pages": range(1, num_pages+1)
        }
    )


def single(request, slug):
    # 文章详细页
    error = None
    article_list = Article.objects.all()
    article_slug = article_list.get(id=slug)
    categories = Category.objects.all()
    article_slug.read_num += 1  # 阅读量增加
    article_slug.save()
    comments = Comments.objects.filter(article=article_slug).order_by('-date_publish')

    if request.method == 'POST':
        form = CommentsForm(request.POST)
        user_name = request.session.get('user_name')
        if form.is_valid() and user_name:
            comment = form.save(commit=False)
            comment.article = article_slug
            comment.user_name = user_name
            comment.save()
        else:
            error = '评论请先登录'
    return render(
        request,
        "boot/blog_single.html",
        {"articles": article_list,
         "articles_slug": article_slug,
         "categories": categories,
         'comments': comments,
         'form': CommentsForm,
         'error': error})


def category_archive(request, slug):
    # 标签页
    categories = Category.objects.all()
    category = get_object_or_404(Category, id=slug)
    page = request.GET.get('page')
    article_queryset = Article.objects.filter(categories=category).order_by('-id')
    articles, num_pages = paginator_page(article_queryset, page)
    return render(
        request,
        "boot/ghost_green.html",
        {"articles": articles,
         "categories": categories,
         "category": category,
         "pages": range(1, num_pages + 1)})


def about(request):
    # 关于页
    category = Category.objects.all()
    return render(request,
                  'boot/about.html',
                  {"categories": category})


def sign_in(request):
    # 注册
    redirect_to = request.GET.get('next', '/')
    if request.method == 'POST':
        form = Nameform(request.POST)
        if form.is_valid():
            vistor = form.save(commit=False)
            vistor.save()
            request.session['user_name'] = vistor.user_name
            return HttpResponseRedirect(redirect_to)
    return render(request,
                  'boot/sign_in.html',
                  {'form': Nameform})


def sign_up(request):
    # 登录
    redirect_to = request.GET.get('next', '/')
    if request.method == 'POST':
        form = Nameform(request.POST)
        if form.is_valid():
            username = form.cleaned_data['user_name']
            password = encryption(form.cleaned_data['password'])
            user = Visitors.objects.filter(user_name__exact=username, password__exact=password)
            if user:
                request.session['user_name'] = username
                return HttpResponseRedirect(redirect_to)
            form.error = '用户不存在请重新输入'
    return render(request, 'boot/sign_in.html', {
        'form': Nameform,

    })


def sign_out(request):
    redirect_to = request.GET.get('next', '/')
    try:
        del request.session['user_name']
    except KeyError:
        pass
    return HttpResponseRedirect(redirect_to)
